<?php
namespace app\controllers;

use Yii;
use app\components\BaseController;
use app\components\Api;
use app\components\Loyalty;
use app\components\JselectLoyalty;
use app\components\JselectLoyaltyUAT;
use app\components\Log;
use app\models\Tenant;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;

class BindingController extends BaseController
{
	public $enableCsrfValidation = false;
	
	/**
	 * existsing member binding
	 */
	public function actionJselect()
	{		
		$appid = Yii::$app->request->get('appid');
		if (!$appid) {
			throw new ServerErrorHttpException('no appid found.');
		}
		
		$openid = Yii::$app->request->get('openid');
		if (!$openid) {
			throw new ServerErrorHttpException('no openid found.');
		}
		$this->session('openid', $openid);
		
		$this->bootstrap($appid);	
			
		$re = Loyalty::customer_get(['wechat_openid' => $openid]);
		if ($re['status'] == 'success') {
			// 已存在用户直接跳转到会员中心
			$url = Url::to(['wechat/oauth/member_index', 'appid' => $appid, 'openid' => $openid]);
			$this->redirect($url);
		} else {
			$this->layout = 'jselect';
			return $this->render('jselect');
		}
	}
	
	/**
	 * send sms validate mobile
	 */
	public function actionSendSms()
	{
		if (Yii::$app->request->isPost && yii::$app->request->isAjax) {				
			$mobile = $_POST['mobile'];
			if (substr($mobile, 0, 1) == '+') {
				$mobile = substr($mobile, 1, strlen($mobile) - 1);
			}
			if (substr($mobile, 0, 2) != '86') {
				$mobile = '86' . $mobile;
			}		
			// 生成隨即6位驗證碼，並寫入session
			$verify_code = '';
			for ($i = 1;$i <= 6;$i++) {
				$verify_code .= rand(0, 9);
			}
// 			$verify_code = '123456';
			Yii::$app->session->set('vf_code_' . $mobile, $verify_code);
// 			$re = ['status' => 'success', 'message' => '发送成功!'];
// 			echo json_encode($re);
// 			echo $verify_code;exit;
			$message = '【JSelect】(验证码)%s，您正在使用尾号为' . substr($mobile, -4, 4) . '的手机号进行绑定微信号操作。';
			$msg = sprintf($message, $verify_code);
		
			//發送短信
			$xmlData = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
			<ShortMessage>
			<UserID>admin@chn.jselect.com</UserID>
			<UserPassword>59jfl438fc</UserPassword>
			<Md5>0</Md5>
			<MessageReceiver>' . $mobile . '</MessageReceiver>
			<MessageBody><![CDATA[' . $msg . ']]></MessageBody>
			<Identifier>smsverifycode</Identifier>
			</ShortMessage>';
			Log::debug('call sending sms API xmlData:', $xmlData);
			// 			$url = 'http://sms-uat.xgate.com:18080/cgi-bin/sendsms?VERBOSE=Disable';
// 			$url = 'https://sms-api.xgate.com/smsc/sendsms?VERBOSE=Disable';
// 			$url = 'http://sms-api.xgate.com/smsc/sendsms?VERBOSE=Disable';
			$url = 'http://sms-api.xgate.com:8280/smsc/sendsms';
// 			$url = 'http://192.168.1.149:8080/cgi-bin/sendsms?VERBOSE=Disable';
			Log::debug('call sending sms API url:', $url);
				
			$ch = curl_init ($url);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'content-type: application/xml',
					'accept: application/json'
			));
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
			//ssl
			//curl_setopt($ch, CURLOPT_SSLVERSION, 3);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			$response = curl_exec($ch);
			Log::debug('call sending sms API result:', $response);
			if (curl_errno($ch)) {
				Log::debug('curl sms api error: ', curl_error($ch));
				$re = ['status' => 'error', 'message' => '发送失败，请稍后重试!'];
				echo json_encode($re);exit;
			}
			curl_close($ch);
		
			$xml = json_decode($response, true);
			Log::debug('curl sms api response xml: ', $xml);
			$res_code = $xml['ShortMessageResponse'][0]['ResponseCode'];
			$res_msg = $xml['ShortMessageResponse'][0]['ResponseMessage'];
			if ($res_msg == 'OK') {
				$re = ['status' => 'success', 'message' => '发送成功!'];
			} else {
				$re = ['status' => 'error', 'message' => '发送失败，请稍后重试 !'];
			}
		} else {
			$re = ['status' => 'error', 'message' => '发送失败，请稍后重试!'];
		}
		
		echo json_encode($re);
	}
	
	/**
	 * check verification_code and update wechat_openid
	 */
	public function actionCheckSubmit()
	{
		if (Yii::$app->request->isPost && yii::$app->request->isAjax) {
			$mobile = $_POST['mobile'];
			if (substr($mobile, 0, 1) == '+') {
				$mobile = substr($mobile, 1, strlen($mobile) - 1);
			}
			if (substr($mobile, 0, 2) != '86') {
				$mobile = '86' . $mobile;
			}
			
			$verification_code = $_POST['verification_code'];
			
			if (Yii::$app->session->has('vf_code_' . $mobile)) {
				$vf_code = Yii::$app->session->get('vf_code_' . $mobile);
				if ($vf_code == $verification_code) {
					if (substr($mobile, 0, 1) == '+') {
						$mobile = substr($mobile, 1, strlen($mobile) - 1);
					}
					if (substr($mobile, 0, 2) != '86') {
						$mobile = '86' . $mobile;
					}
					$re = Loyalty::customer_get(['mobile' => $mobile]);
					if ($re['status'] == 'success') {
						$wechat_openid = $re['wechat_openid'];
						$openid = $this->getOpenid();
						if (empty($wechat_openid)) {
							$update = Loyalty::customer_update(['code' => $re['membership']['code'], 'wechat_openid' => $openid]);
							if ($update['status'] == 'success') {
								$url = Url::to(['wechat/oauth/member_index', 'appid' => $this->getAppid(), 'openid' => $this->getOpenid()]);
								$re = ['status' => 'success', 'message' => '绑定成功!', 'redirect_url' => $url];
							} else {
								$re = ['status' => 'error', 'message' => '绑定失败，请稍后再试!'];
							}
						} else {
							$re = ['status' => 'error', 'message' => '该手机号已绑过，不能再次绑定!'];
						}
					} else {
						$re = ['status' => 'error', 'message' => '该手机号不存在!'];
					}
				} else {
					$re = ['status' => 'error', 'message' => '验证码错误!'];
				}
			} else {
				$re = ['status' => 'error', 'message' => '手机号与验证码不匹配!'];
			}
		} else {
			$re = ['status' => 'error', 'message' => '无效请求!'];
		}
		
		echo json_encode($re);
	}
	
	
	/**
	 * bootLoyaltySession
	 * @param unknown_type $tenant_id
	 * @param unknown_type $account_id
	 * @param unknown_type $username
	 * @param unknown_type $password
	 * @param unknown_type $url
	 */
	protected function bootLoyaltySession($tenant_id, $account_id, $username, $password, $url)
	{
		$session = Yii::$app->session;
		$loyaltyConfig = [
			'tenant_id' => $tenant_id,
			'loyalty_accountid' => $account_id,
			'loyalty_username' => $username,
			'loyalty_password' => $password,
			'loyalty_url' => $url,
		];
		$session->set('loyaltyConfig', $loyaltyConfig);
	}
		
	/**
	 * bootstrap function for basic appid, userinfo
	 * @param string $appid
	 * @param array $userInfo
	 * @throws ServerErrorHttpException
	 */
	protected function bootstrap($appid)
	{
		if (empty($appid)) {
			throw new ServerErrorHttpException('appid not found');
		}
		// 重要！获取appid，作为全局支持
		$this->setAppid($appid);
		
		// 设置identifier
		$tenant = Tenant::find()->where(['appid' => $appid])->one();
		
		if (empty($tenant->identifier)) {
			throw new ServerErrorHttpException('identifier not found');
		}
		$this->setIdentifier($tenant->identifier);
		
		// 设置loyalty config
		if (empty($tenant->tenant_id) || empty($tenant->loyalty_accountid) || empty($tenant->loyalty_username) || empty($tenant->loyalty_password)) {
			throw new ServerErrorHttpException('loyalty config not found');
		} else {
			$session = Yii::$app->session;
			$loyaltyConfig = [
				'tenant_id' => $tenant->tenant_id,
				'app_id' => $tenant->appid,
				'loyalty_accountid' => $tenant->loyalty_accountid,
				'loyalty_username' => $tenant->loyalty_username,
				'loyalty_password' => $tenant->loyalty_password,
				'loyalty_url' => $tenant->loyalty_url,
			];
			$session->set('loyaltyConfig', $loyaltyConfig);
		}
	}
	

}